<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'

// 假设 contentData 是从其他地方导入的数据

import { lStorage } from '@/utils/storage'

import AboutUs from '@/views/AboutUs/AboutUs/index.vue'
import PreviewOfAchievements from '@/views/AboutUs/PreviewOfAchievements/index.vue'

import { useTabsStore } from '@/store/modules/tabs'

import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const tabs = ref([
	{
		id: 'AboutUs',
		title: '',
	},
	{
		id: 'PreviewOfAchievements',
		title: 'routes.AboutUs.PreviewOfAchievements',
		content: 'AboutUs.PreviewOfAchievements.content',
	},
])

const isPC = ref(false)

const activeTab = ref('')
const observer = ref(null)

const isStartScrolling = ref(true)

// 监听标题的变化
watch(
	() => lStorage.getReactive().value.WX_ACTIVE_TAB,
	(newVal) => {
		nextTick(() => {
			const tab = newVal.split('/').filter(Boolean)
			if (newVal.includes('AboutUs') && tab.length > 1) {
				activeTab.value = tab[1]
			} else if (newVal.includes('AboutUsIndex')) {
				lStorage.set('temporaryPath', null)
				useTabsStore().setActiveTab(`/AboutUs`)
				activeTab.value = ''
			}
		})
	},
	{ immediate: true, deep: true } // 添加 immediate 选项处理初始值
)

// 监听标题的变化
watch(
	() => lStorage.getReactive().value.isStartScrolling,
	(newVal) => {
		nextTick(() => {
			isStartScrolling.value = newVal
		})
	},
	{ immediate: true, deep: true } // 添加 immediate 选项处理初始值
)

// 设置活跃标签
const setActiveTab = (id) => {}

const setupIntersectionObserver = () => {
	if (observer.value) observer.value.disconnect()

	// 添加延迟确保元素存在
	setTimeout(() => {
		const targets = tabs.value
			.map((tab) => document.getElementById(tab.id))
			.filter(Boolean)

		if (targets.length === 0) {
			return
		}

		observer.value = new IntersectionObserver(
			(entries) => {
				entries.forEach((entry) => {
					if (entry.isIntersecting) {
						lStorage.set('temporaryPath', entry.target.id)
						lStorage.set('isStartScrolling', false)
						useTabsStore().setActiveTab(`/AboutUs/${entry.target.id}`)
					}
				})
			},
			{
				root: null,
				rootMargin: '-40px 0px -60% 0px',
				threshold: 0.01,
			}
		)

		targets.forEach((el) => {
			console.log('Observing element:', el.id) // 调试用
			observer.value.observe(el)
		})
	}, 0) // 100ms 延迟
}

let isScrolling = false
watch(
	activeTab,
	(newVal, oldVal) => {
		if (isStartScrolling.value) {
			if (isScrolling || newVal === oldVal) return

			isScrolling = true
			nextTick(() => {
				const target = document.getElementById(newVal)
				if (target) {
					target.style.scrollMarginTop = isPC.value ? `300px` : '20px' // 动态设置
					target?.scrollIntoView({
						behavior: 'smooth',
						block: 'start',
						inline: 'nearest',
					})
				}

				setTimeout(() => (isScrolling = false), 500)
			})
		}
	},
	{
		deep: true,
	}
)
// AOS 初始化 + 滚动锚点处理
onMounted(async () => {
	await nextTick(() => {
		// 新锚点处理逻辑
		document.querySelectorAll('a[data-anchor]').forEach((anchor) => {
			anchor.addEventListener('click', function (e) {
				e.preventDefault()
				const targetId = this.dataset.anchor // 直接获取绑定的 ID
				setActiveTab(targetId) // 同步更新 activeTab 状态
			})
		})

		setTimeout(() => {
			// 检查 URL 或存储中的初始状态
			const initialTab = lStorage.get('temporaryPath') || ''
			if (initialTab) {
				activeTab.value = initialTab
				useTabsStore().setActiveTab(`/AboutUs/${initialTab}`)
			}
		}, 0)
		setupIntersectionObserver()
	}) // 等待下一个 tick 确保 DOM 更新

	// 判断设备类型（可根据需求调整阈值）
	isPC.value = window.matchMedia('(min-width: 992px)').matches
	// 监听窗口变化
	window.addEventListener('resize', () => {
		isPC.value = window.matchMedia('(min-width: 992px)').matches
	})

	// 滚动时高亮当前章节对应的导航按钮
	window.addEventListener('scroll', function () {
		const sections = document.querySelectorAll('.section')
		const navBtns = document.querySelectorAll('.nav-btn')

		let current = ''

		sections.forEach((section) => {
			const sectionTop = section.offsetTop - 200
			const sectionHeight = section.offsetHeight
			if (
				window.pageYOffset >= sectionTop &&
				window.pageYOffset < sectionTop + sectionHeight
			) {
				current = section.getAttribute('id')
			}
		})

		navBtns.forEach((btn) => {
			btn.classList.remove('active')
			if (btn.getAttribute('data-target') === current) {
				btn.classList.add('active')
			}
		})
	})

	// 点击导航按钮时的平滑滚动
	document.querySelectorAll('.nav-btn').forEach((btn) => {
		btn.addEventListener('click', function (e) {
			e.preventDefault()
			const target = document.querySelector(this.getAttribute('href'))
			const headerHeight = 140 // 头部和导航的总高度
			const targetPosition = target.offsetTop - headerHeight

			window.scrollTo({
				top: targetPosition,
				behavior: 'smooth',
			})
		})
	})

	// 页面加载完成后的入场动画
	window.addEventListener('load', function () {
		document.querySelectorAll('.nav-btn').forEach((btn, index) => {
			setTimeout(() => {
				btn.style.opacity = '1'
				btn.style.transform = 'translateY(0)'
			}, index * 100)
		})
	})
})
// 清理 Observer
onBeforeUnmount(() => {
	if (observer.value) {
		observer.value.disconnect()
	}
})
</script>

<template>
	<div class="product-container">
		<div class="quick-nav" v-if="false">
			<div class="quick-nav-container">
				<div class="nav-title">{{ t('AboutUs.nav') }}</div>
				<div class="nav-buttons">
					<a
						:href="`#${item.id}`"
						class="nav-btn"
						:data-target="item.id"
						v-for="(item, index) in tabs"
						:key="index"
					>
						<div class="nav-btn-icon"></div>
						<div class="nav-btn-text">
							<div class="nav-btn-title">{{ t(item.title) }}</div>
						</div>
					</a>
				</div>
			</div>
		</div>

		<section
			class="content-section section"
			v-for="(item, index) in tabs"
			:key="index"
			:id="item.id"
		>
			<div class="container">
				<h2 class="section-title" v-if="item.title !== ''">
					{{ t(item.title) }}
				</h2>
				<div class="service-text" v-if="item.content">
					<p>{{ t(item.content) }}</p>
				</div>

				<AboutUs v-show="item.id === 'AboutUs'" />
				<PreviewOfAchievements v-show="item.id === 'PreviewOfAchievements'" />
			</div>
		</section>
	</div>
</template>

<style scoped lang="scss">
/*
 * ===========================================
 * 关于我们模板样式 - AboutUs/Template.vue
 * ===========================================
 */

.product-container {
	position: relative;
}

/* ===========================================
 * 内容区域样式
 * =========================================== */

.content-section {
	padding: var(--space-20) 0;
	position: relative;

	&:nth-child(even) {
		background: var(--content-bg-alt);
	}

	.container {
		max-width: 1200px;
		margin: 0 auto;
		box-sizing: border-box;
		padding: 0 var(--space-4);
	}

	.section-title {
		text-align: center;
		font-size: var(--font-size-4xl);
		font-weight: var(--font-weight-bold);
		color: var(--text-title);
		margin-bottom: var(--space-8);
		line-height: var(--line-height-tight);
	}

	.service-text {
		text-align: center;
		max-width: 800px;
		margin: 0 auto var(--space-8);

		p {
			font-size: var(--font-size-lg);
			color: var(--text-secondary);
			line-height: var(--line-height-relaxed);
			margin: 0;
		}
	}
}

/* ===========================================
 * 快速导航样式（已隐藏但保留）
 * =========================================== */

.quick-nav {
	background: var(--nav-bg);
	padding: var(--space-10) 0;
	box-shadow: var(--nav-shadow);
	position: sticky;
	top: 70px;
	z-index: var(--z-modal);
	border-bottom: 1px solid var(--nav-border);
	backdrop-filter: var(--nav-backdrop);

	.quick-nav-container {
		max-width: 1200px;
		margin: 0 auto;
		padding: 0 var(--space-4);
	}

	.nav-title {
		text-align: center;
		margin-bottom: var(--space-8);
		color: var(--text-heading);
		font-size: var(--font-size-lg);
		font-weight: var(--font-weight-semibold);
	}

	.nav-buttons {
		display: grid;
		justify-content: center;
		gap: var(--space-6);
		grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
	}

	.nav-btn {
		background: var(--card-bg);
		border: 2px solid var(--card-border);
		color: var(--text-primary);
		padding: var(--space-6) var(--space-8);
		border-radius: var(--radius-2xl);
		text-decoration: none;
		font-weight: var(--font-weight-semibold);
		transition: all var(--transition-base);
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: var(--space-3);
		position: relative;
		overflow: hidden;
		backdrop-filter: var(--card-backdrop);

		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: -100%;
			width: 100%;
			height: 100%;
			background: var(--brand-primary-100);
			transition: left var(--duration-500);
		}

		&:hover::before {
			left: 100%;
		}

		&:hover {
			background: var(--brand-primary);
			color: var(--color-white);
			border-color: var(--brand-primary);
			transform: translateY(-3px);
			box-shadow: var(--shadow-lg);
		}

		&.active {
			background: var(--brand-primary);
			color: var(--color-white);
			border-color: var(--brand-primary);
			box-shadow: var(--shadow-lg);
		}

		.nav-btn-icon {
			width: 45px;
			height: 45px;
			border-radius: var(--radius-xl);
			display: flex;
			align-items: center;
			justify-content: center;
			background: var(--brand-primary-50);
			border: 2px solid var(--card-border);
			transition: all var(--transition-base);
		}

		&:hover .nav-btn-icon,
		&.active .nav-btn-icon {
			background: rgba(255, 255, 255, 0.2);
			border-color: rgba(255, 255, 255, 0.3);
		}

		.nav-btn-text {
			text-align: center;
			line-height: var(--line-height-snug);

			.nav-btn-title {
				font-size: var(--font-size-base);
				margin-bottom: var(--space-1);
			}
		}
	}
}

/* 锚点定位偏移修正 */
:target {
	scroll-margin-top: 280px !important;
}

/* ===========================================
 * 响应式设计
 * =========================================== */

@media (max-width: var(--breakpoint-md)) {
	.content-section {
		padding: var(--space-16) 0;

		.container {
			padding: 0 var(--space-3);
		}

		.section-title {
			font-size: var(--font-size-3xl);
			margin-bottom: var(--space-6);
		}

		.service-text p {
			font-size: var(--font-size-base);
		}
	}

	.quick-nav {
		padding: var(--space-6) 0;

		.nav-buttons {
			grid-template-columns: 1fr;
			gap: var(--space-4);
		}

		.nav-btn {
			padding: var(--space-4) var(--space-6);
		}
	}

	:target {
		scroll-margin-top: 200px !important;
	}
}

@media (max-width: var(--breakpoint-sm)) {
	.content-section {
		padding: var(--space-12) 0;

		.section-title {
			font-size: var(--font-size-2xl);
		}

		.service-text p {
			font-size: var(--font-size-sm);
		}
	}

	:target {
		scroll-margin-top: 150px !important;
	}
}
</style>
